package cn.ctyun.ipush.controller;

import cn.ctyun.ipush.model.ExcelModel;
import cn.ctyun.ipush.service.ExcelService;
import cn.ctyun.ipush.vo.ExcelVo;
import com.dexcoder.commons.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-7-11
 * Time: 上午10:33
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class ExcelFileController {

    @Autowired
    private ExcelService excelService;

    @RequestMapping(value = "/uploadOneFile", method = RequestMethod.GET)
    public String uploadFile() {
        return "uploadOneFile";
    }

    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String uploadFileHandler(HttpServletRequest request, Model model,
                                    @RequestParam("file") MultipartFile[] files) {

        String fileName=null; //原始文件名
        String filePath=null; //完整的文件路径
        String createUserid=null; //创建用户ID
        String excelName=null;//修改后的文件名 createUserId_filename

        // Root Directory.
        String uploadRootPath = request.getRealPath("/") + "upload";

        System.out.println("uploadRootPath=" + uploadRootPath);

        File uploadRootDir = new File(uploadRootPath);
        //
        // Create directory if it not exists.
        if (!uploadRootDir.exists()) {
            uploadRootDir.mkdirs();
        }
        //
        List<File> uploadedFiles = new ArrayList<File>();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];

            // Client File Name
            String name = file.getOriginalFilename();
            fileName=name;
            System.out.println("Client File Name = " + name);

            if (name != null && name.length() > 0) {
                try {
                    byte[] bytes = file.getBytes();

                    // Create the file on server
                    filePath=uploadRootDir.getAbsolutePath()+ File.separator + createUserid+"_"+name;
                    excelName= createUserid+"_"+name;

                    File serverFile = new File(filePath);

                    // Stream to write data to file in server.
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                    //
                    uploadedFiles.add(serverFile);
                    System.out.println("Write file: " + serverFile);
                } catch (Exception e) {
                    System.out.println("Error Write file: " + name);
                }
            }
        }
        //Excel store to DB
        ExcelModel excelModel=new ExcelModel();
        excelModel.setExcelPath(filePath);
        excelModel.setTemplateName(fileName);
        excelModel.setExcelName(excelName);
        excelModel.setCreateUserid(createUserid);

        ExcelVo excelVo=new ExcelVo();
        excelVo.setExcelName(excelName);
        if(!excelService.isExist(excelVo)){
            excelService.save(excelModel);
        }else{
            throw new RuntimeException("名称已存在");
        }
        model.addAttribute("uploadedFiles", uploadedFiles);
        return "uploadResult";
    }

    @RequestMapping(value = "/download", method = RequestMethod.POST)
    public void downLoad(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // Root Directory.
        String uploadRootPath = request.getRealPath("/") + "upload";

        //获取要下载的文件名
        String filename = request.getParameter("name");
        filename = "1.xlsx";
        //得到想客服端输出的输出流
        OutputStream outputStream = null;
        FileInputStream inputStream = null;
        try {
            outputStream = response.getOutputStream();

            //输出文件用的字节数组，每次向输出流发送600个字节
            byte b[] = new byte[1000];
            //要下载的文件
            File fileload = new File(uploadRootPath, filename);
            //这里对文件名进行编码，保证下载时汉字显示正常
            String fileName = URLEncoder.encode(filename, "utf-8");
            //客服端使用保存文件的对话框
            response.setHeader("Content-disposition", "attachment;filename=" + filename);
            //通知客服文件的MIME类型
            response.setContentType("application/msword");
            response.setCharacterEncoding("utf-8");
            //通知客服文件的长度
            long fileLength = fileload.length();
            String length = String.valueOf(fileLength);
            response.setHeader("Content_length", length);
            //读取文件，并发送给客服端下载
            inputStream = new FileInputStream(fileload);
            int n = 0;
            while ((n = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, n);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            if (null != outputStream)
                outputStream.close();
            if (null != inputStream)
                inputStream.close();
        }
    }




}
